<?php





namespace app\admin\model;

use app\crm\model\CustomerLossModel;
use app\crm\model\ReserveandLost;
use think\facade\Db;




class SysModel extends Common

{



    /**

     * @var string

     */

    protected $name = 'admin_sys';



    protected $defaultSoftDelete = 0;



    protected $autoWriteTimestamp = true;



    /**

     * 获取系统首页信息资源

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */

    public function getAdminSysHomeInfoResource($shopIds,$request): array

    {

		// 月初流失预警顾客
		if($request['startTime']){
			$start_time = $request['startTime'];
		}else{
			$start_time = date("Y-m-01",time());
		}

		// echo $start_time;
		// exit;
       /* echo "<pre>";
        print_r($request);
        exit;
 */
        // echo "<pre>";
        // print_r($request);exit;

        $today = date('Y-m-d',time());

        $orderModel = new ShopOrderModel();

        $customerModel = new CustomerModel();

        // $customerLossModel = new CustomerLossModel();

        $model = new ReserveandLost();
		// print_r("阶段1:".time().PHP_EOL);
        $orderCollect =$orderModel->getShopOrderCommonDataCollect($shopIds,$request);
		// print_r("阶段2:".time().PHP_EOL);
        $customerCollect =$customerModel->getCustomerCommonDataCollect($shopIds,$request);
		// print_r("阶段3:".time().PHP_EOL);
        // exit;
        // 2022-04-27

		$newRequest_t = [];
		// $newRequest_t['cj_time'] = $request['startTime'] ?? '';


        // $request_loss_one = $request;
        // $request_loss_one['shopIds'] = $shopIds;
        // $request_loss_one['is_join_shop'] = '4'; // 流失预警

        // $customerLossOne = $customerLossModel->getDataList($request_loss_one);

        // $request_loss_two = $request;
        // $request_loss_two['shopIds'] = $shopIds;
        // $request_loss_two['is_join_shop'] = '3'; // 流失顾客

        // $customerLossTwo = $customerLossModel->getDataList($request_loss_two);

        if($shopIds){

            $cj_customerIds = $model->cj_customer($shopIds,$newRequest_t);

        }else{

            $shop_where = [];

            array_push($shop_where,['shop_type','=','2']);

            array_push($shop_where,['type','<>','2']);

            array_push($shop_where,['status','=','1']);

            $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

            $cj_customerIds = $model->cj_customer($shopIds,$newRequest_t);

        }

        $yj_customerIds = $model->warning_customer($cj_customerIds,$today,'','',''); // 流失预警

        $ls_customerIds = $model->lost_customer($cj_customerIds,$today); // 流失顾客

        $by_customerIds = $model->baoyou_customer($cj_customerIds,$today); // 保有顾客



		$warn_customerIds = $model ->warning_customer('','','back',$shopIds,$start_time); // 月初流失预警顾客

		$over_time = time();

		$back_customerIds = $model ->back_customer($warn_customerIds,$start_time,$over_time);

		//$cjCustomerNum = count($cj_customerIds);                   //成交客户
		/* echo '<pre>';
		print_r($cj_customerIds);

		exit; */

        if($orderCollect['sysDealNumber'] == 0){

            //$orderCollect['sysDealNumber']=1;

        }

        return [

            'sysCurrentPerformance' => round($orderCollect['sysCurrentPerformance'],2),  //当前店铺集合支付总金额

            'sysCompleteNewOrder' => round($orderCollect['sysCompleteNewOrder'],2), //新单

            'sysCompleteSupplement' => round($orderCollect['sysCompleteSupplement'],2),//补单

            'sysNewOrderTurnoverRate' => $customerCollect['sysFinishEnterStore'] == '0' ? '0%' : (round($orderCollect['sysDealNumber']/$customerCollect['sysFinishEnterStore'],2)*100).'%',

            'sysDealNumber' => $orderCollect['sysDealNumber'],  //当前店铺集合支付总订单数量 成交量

			'sysDealNumberEcharts' => $orderCollect['sysDealNumberEcharts'],  // 当前店铺集合支付总订单数量 成交量（疤痕痘痘项目）

            'sysFinishEnterStore' => $customerCollect['sysFinishEnterStore'], // 进店

			'sysFinishEnterStoreEcharts' => $customerCollect['sysFinishEnterStoreEcharts'], // 进店 (疤痕痘痘项目)

            'referralsCout'=>$customerCollect['customerTenureNumber'],

            'sysOnlineStoreEntryRate' => $customerCollect['sysOnlineStoreEntryRate'],

            'customerNumber' => $customerCollect['customerNumber'],

            'customerBirthNumber' => $customerCollect['customerBirthNumber'],

            'customerRevisitedCount' => $customerCollect['customerVisitedNumber'],

            // 'customerTenureNumber' => $customerCollect['tenure'],

            // 'customerDrainNumber' => $customerLossTwo['dataCount'],

            // 'customerWarnNumber' => $customerLossOne['dataCount'],

			'customerCJNumber' => count($cj_customerIds),  //成交客户

            'customerTenureNumber' => count($by_customerIds),

            'customerDrainNumber' => count($ls_customerIds),

            'customerWarnNumber' => count($yj_customerIds),

			'customerRetentionRate' => count($cj_customerIds)>0 ? bcmul(bcdiv(count($by_customerIds),count($cj_customerIds),4),100,2).'%' : '0%',  //保有率

			'back_warn_Rate' => count($warn_customerIds)>0 ? bcmul(bcdiv(count($back_customerIds),count($warn_customerIds),4),100,2).'%' : '0%',  //当月预警回流率

        ];

    }

    /**

     * 获取员工业绩

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysHomePersonAchieveResource($shopIds,$request)

    {


		$start_time = $request['startTime'] ?? '';
		$end_time = $request['endTime'] ?? '';

		if($start_time){

			 $startTime = strtotime($start_time." 00:00:00");
			 $endTime = strtotime($end_time." 23:59:59");

		}else{
			$startTime = strtotime(date('Y-m-01',time()));
			$endTime = strtotime(date('Y-m-t 23:59:59',time()));
		}

		$shopId = $request['shopId'] ?? '';

        /* $personModel = new PersonModel();

        $list =$personModel->getPersonAdminListResourceServiceSys($shopIds,$request,1,10); */

		if($shopIds){

			//echo 'jinru';exit;

			$newRequest['shop_id'] = $shopId;

			$newRequest['startTime'] = $startTime;
			$newRequest['endTime'] = $endTime;

			$staffList = Db::name('shop_person')->alias('sp')

				->join('admin_user au', 'au.shop_person_id = sp.id', 'LEFT')

				->where('au.is_status',0)

				->where('sp.shop_id',$shopId)

				->where('sp.position_id','in',[3,4,7,8,9])

				->column('sp.id,sp.name');

			$newRequest['staffList'] = $staffList;

			$rexinMoney = $this->newOrder($newRequest); //新单数据
			$rebuMoney = $this->repairOrder($newRequest); //补单数据

			$experienceMoney = $this->experience($newRequest); //体验成交

			$referralMoney = $this->zhuanNums($newRequest); //体验成交

			$waiLianMoney = $this->waiLianNums($newRequest); //外联人数

			$serviceLogNum = $this->serviceLog($newRequest); //外联人数


			foreach ($staffList as $key => $value) {

				$staffList[$key]['newOrder'] =  $rexinMoney[$value['id']]['newOrder'];

				$staffList[$key]['repairOrder'] =  $rebuMoney[$value['id']]['repairOrder'];

				$staffList[$key]['experience'] =  $experienceMoney[$value['id']]['experience'];

				$staffList[$key]['referral'] =  $referralMoney[$value['id']]['zhuanNums'];

				$staffList[$key]['waiLianNums'] =  $waiLianMoney[$value['id']]['waiLianNums'];

				$staffList[$key]['serviceLog'] =  $serviceLogNum[$value['id']]['serviceLog'];

			}

			return ['list' => $staffList];
		}else{

			return ['list' => ''];

		}
    }



	// 新单业绩
	public function newOrder($request)
	{

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

		$staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['order_type','=',1], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',2], ['status','=',2], ['order_type','=',1], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	   $list = [];
	    foreach ($staff_ids as $key => $value) {

	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';


			$list[$value]['name'] = $staff_name[$value] ?? '';

			$list[$value]['newOrder'] = bcsub($shouKuan,$tuiKuan,2);

	    }

		return $list;
	}

	// 补单业绩
	public function repairOrder($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['order_type','=',2], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',1], ['status','=',2], ['order_type','=',2], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

			$list[$value]['name'] = $staff_name[$value] ?? '';

			$list[$value]['repairOrder'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;
	}

	// 体验成交
	public function experience($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_experience', '=', 1], ['experience_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['refund_type','=','101.02 ']])->group('experience_id')->column('sum(pay_amount) as sum','experience_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_experience', '=', 1], ['experience_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',2], ['status','=',2], ['refund_type','=','101.02 ']])->group('experience_id')->column('sum(pay_amount) as sum','experience_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['experience'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;
	}

	// 转介绍数
	public function zhuanNums($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_introduction', '=', 1], ['introduction_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['refund_type','=','101.02 ']])->group('introduction_id')->column('sum(pay_amount) as sum','introduction_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_introduction', '=', 1], ['introduction_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',2], ['status','=',2], ['refund_type','=','101.02 ']])->group('introduction_id')->column('sum(pay_amount) as sum','introduction_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['zhuanNums'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;

	}

	// 外联人数
	public function waiLianNums($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('customer')->where([['shop_id', 'in', $shop_id], ['outreach_id', 'in', $staff_ids], ['first_time|second_time', 'between', "$start_time,$end_time"]])->group('outreach_id')->column('count(*) as sum','outreach_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['waiLianNums'] = $list1[$value] ?? '0';

	    }
	    return $list;
	}

	// 护理次数
	public function serviceLog($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', 'in', $staff_ids], ['nurse_id_two', '=', 0], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_one')->column('count(*) as sum','nurse_id_one');

	    $list2 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', 'in', $staff_ids], ['nurse_id_two', '>', 0], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_one')->column('count(*)*0.5 as sum','nurse_id_one');

	    $list3 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', '>', 0], ['nurse_id_two', 'in', $staff_ids], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_two')->column('count(*)*0.5 as sum','nurse_id_two');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {

	        $num1 = $list1[$value] ?? '0';

	        $num2 = $list2[$value] ?? '0';

	        $num3 = $list3[$value] ?? '0';

	        $hezuo = bcadd($num2,$num3);

			$list[$value]['name'] = $staff_name[$value] ?? '';
			$list[$value]['serviceLog'] = bcadd($num1,$hezuo);

	    }
	    return $list;
	}
    /**

     * 获取系统信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysServerInfoResource()

    {

        $serverInfo = $this->where('name', 'system')->value('value');

        return json_decode($serverInfo, true);

    }



    /**

     * 获取系统登录日志

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysLoginLogResource()

    {

        $record = new RecordModel();

        return $record->page(1, 3)->select();

    }



    /**

     * 获取系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysUserResource($userId)

    {

        $field = ['id', 'username', 'email'];

        $user = new UserModel();

        return $user->field($field)->where('id', $userId)->find();

    }

    /**

     * 获取系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysUserInfoResource($userId)

    {

        $field = ['id', 'username', 'email','img','thumb_img'];

        $user = new UserModel();

        return $user->field($field)->where('id', $userId)->find();

    }



    /**

     * 更新系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function updateAdminSysUserResource($request,$userId)

    {

        $field = ['id', 'salt', 'username', 'password', 'email'];

        $user = new UserModel();

        $info = $user->field($field)->where('id', $userId)->find();

        $encryOldPass = user_md5($request['oldPass'], $info['salt'], $info['username']);

        if ($encryOldPass != $info['password']) {

            $this->error = '您输入原始密码不正确';

            return false;

        }

        if ($request['newPass'] != $request['confirmPass']) {

            $this->error = '您两次输入的密码不一致,请检查';

            return false;

        }

        $data = [

            'id' => $info['id'],

            'email' => $request['email']??'',

            'img' => $request['img']??'',

            'thumb_img' => $request['thumb_img']??'',

            'password' => user_md5($request['newPass'], $info['salt'], $info['username']),

        ];

        $user->update($data);

        return true;

    }

}
